<template>
  <div class="menu-management-container">
    <el-row :gutter="20">
      <!--  <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
       <vab-card shadow="hover">
          <el-tree
            :data="data"
            :default-expanded-keys="expandDefault"
            highlight-current
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>-->
      <el-col :lg="24" :md="18" :sm="24" :xl="24" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="24">
              <el-form inline :model="queryForm" @submit.prevent>
                <el-form-item class="mr10">
                  <span class="w120">旧物料名称：</span>
                  <el-input
                    v-model.trim="queryForm.search"
                    class="w164"
                    clearable
                    :placeholder="translate('请输入旧物料名称')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <span class="w120">旧物料编码：</span>
                  <el-input
                    v-model.trim="queryForm.search3"
                    class="w164"
                    clearable
                    :placeholder="translate('请输入旧物料编码')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <!-- <el-input
                    class="mr10"
                    v-model.trim="queryForm.search1"
                    clearable
                    :placeholder="translate('请输入单位')"
                    @keyup.enter="fetchData('search')"
                  /> -->
                  <span class="w120">单位：</span>
                  <el-autocomplete
                    v-model.trim="queryForm.search4"
                    class="inline-input mr10"
                    :fetch-suggestions="querySearch"
                    placeholder="选择单位"
                    @select="handleSelect"
                  />
                </el-form-item>
                <el-form-item>
                  <span class="w120">新物料名称：</span>
                  <el-input
                    v-model.trim="queryForm.search2"
                    class="ml10 w164"
                    clearable
                    :placeholder="translate('请输入新物料名称')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <span class="w120">新物料编码：</span>
                  <el-input
                    v-model.trim="queryForm.search1"
                    class="ml10 w164"
                    clearable
                    :placeholder="translate('请输入新物料编码')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <div>
                <el-form-item>
                  <span class="w120">大类编码：</span>
                  <el-input
                    v-model.trim="queryForm.searchBigCateCode"
                    class="w164"
                    clearable
                    :placeholder="translate('请输入大类编码')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <span class="w120">有效期：</span>
                  <el-input
                    v-model.trim="queryForm.searchValidDate"
                    class="w164"
                    clearable
                    :placeholder="translate('请输入有效日期')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <span class="w120">创建时间：</span>
                  <el-date-picker
                  v-model="queryForm.search5"
                  end-placeholder="结束日期"
                  range-separator="至"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="fetchData('search')"
                  >
                    {{ translate('查询') }}
                  </el-button>
                  <el-button
                    type="primary"
                    @click="resetFn()"
                  >
                    {{ translate('重置') }}
                  </el-button>
                </el-form-item>
                </div>
              </el-form>
            </vab-query-form-top-panel>
          </vab-query-form>
          <div class="add">
            <el-button
                v-if="MenuAuth('add')"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
              <!-- <el-button type="primary" @click="download()" plain>
                    {{ translate('下载') }}
              </el-button> -->
              <el-upload
                    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    :action="action"
                    :before-upload="beforeUpload"
                    class="ml"
                    :headers="headers"
                    name="fileInput"
                    :on-error="handleError"
                    :on-success="handleSuccess"
                    :show-file-list="false"
                  >
                  <el-button type="primary" @click="uploadFn()" plain>
                      {{ translate('导入') }}
                  </el-button>
              </el-upload>
              <el-button type="primary" @click="exportFn('search')" plain>
                    {{ translate('导出') }}
              </el-button>
              <el-button type="primary" @click="deletedBatchFn()" plain>
              {{ translate('批量删除') }}
              </el-button>
              <el-button type="primary" @click="deletedSX()" plain>
              {{ translate('筛选删除') }}
              </el-button>
          </div>
          <el-table
          v-loading="listLoading"
          border
          :data="list"
          :row-class-name="tableRowClassName"
          :row-key="getRowKey"
          @selection-change="handleSelectionChange">
            <el-table-column prop="value" type="selection" width="55" />
            <el-table-column :label="translate('序号')" type="index" width="auto" />
            <el-table-column
              :label="translate('大类编码')"
              prop="BigCateCode"
              show-overflow-tooltip
            />
            <el-table-column :label="translate('旧物料编码')">
              <template #default="{ row }">
                <div>
                  <span class="iconcolor">{{ row.OldCode }}</span>
                  <vab-icon icon="file-copy-line" @click="copyToClipboard(row.OldCode)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="translate('旧物料长描述')">
              <template #default="{ row }">
                <div>
                  <span class="iconcolor">{{ row.OldSpec }}</span>
                  <vab-icon icon="file-copy-line" @click="copyToClipboard(row.OldSpec)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('旧物料基本单位')"
              prop="OldUnit"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('清洗单位')"
              min-width="92"
              prop="WHUnit"
              show-overflow-tooltip
            />
            <el-table-column :label="translate('新品名')">
              <template #default="{ row }">
                <div>
                  <span class="iconcolor">{{ row.NewName }}</span>
                  <vab-icon icon="file-copy-line" @click="copyToClipboard(row.NewName)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('新品名描述')"
              min-width="92"
              prop="NewSpec"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('基本单位')"
              min-width="92"
              prop="BaseUnit"
              show-overflow-tooltip
            />
            <el-table-column :label="translate('新编码')">
              <template #default="{ row }">
                <div>
                  <span class="iconcolor">{{ row.NewCode }}</span>
                  <vab-icon icon="file-copy-line" @click="copyToClipboard(row.NewCode)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="translate('新备注')">
              <template #default="{ row }">
                <div>
                  <span class="iconcolor">{{ row.NewRemark }}</span>
                  <vab-icon icon="file-copy-line" @click="copyToClipboard(row.NewRemark)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('有效日期')"
              prop="ValidDate"
              show-overflow-tooltip
              min-width="170"
            />
            <el-table-column
              :label="translate('备注')"
              prop="Remark"
              show-overflow-tooltip
            />
            <el-table-column :label="translate('是否有效')">
              <template #default="{ row }">
                <div>{{row.Enabled === 0 ? '否' : '是'}}</div>
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('创建人')"
              prop="CreateUserName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('创建时间')"
              prop="CreateDate"
              show-overflow-tooltip
              min-width="170"
            />
            <el-table-column
              align="center"
              :label="translate('操作')"
              show-overflow-tooltip
              width="180"
            >
              <template #default="{ row }">
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                  plain
                >
                  {{ translate('编辑') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>
    <edit
      ref="editRef"
      :parent-list="data"
      :tree="tree"
      @fetch-data="fetchData"
    />
    <el-dialog
      v-model="dialogVisible1"
      :before-close="handleClose1"
      :title="translate('筛选时间')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <span class="txr">时间：</span>
        <el-date-picker
              v-model="searchInfo"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
              />
      </div>
      <template #footer>
        <el-button @click="handleClose1">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm1">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    DelItem,
    wms_itemData,
    Wms_itemDown,
    Wms_All_ItemExport,
    BaseGetPageData,
    BatchDelItem,
    SelAllItemWHUnit,
    DateDelAllItem
  } from '@/api/item'
  import { getTree } from '@/api/companyManagement'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { useSettingsStore } from '@/store/modules/settings'
  import { MenuAuth } from '~/src/utils/permission'
  import { parseTime } from '@/utils'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import { translate } from '@/i18n'
  const { token } = useUserStore()
  import Dialog from './components/ItemEdit.vue'

  export default defineComponent({
    name: 'Item',
    components: {
      edit: Dialog,
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        editRef: null,
        data: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        list: [],
        tree: [],
        selectArr: [],
        dialogVisible1: false,
        searchInfo: [],
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          total: 0,
          tableName: "",
          sort: "",
          order: "",
          wheres: "",
          export: false,
          value: "",
          openid: ""
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        listLoading: true,
        expandDefault: [],
        headers: {},
        action: '',
        WHdata: [],
      })
      const handleSelect = (item) => {
        console.log(item)
      }
      const tableRowClassName = ({ row, rowIndex }) => {
        row.row_index = rowIndex
      }
      const handleSelectionChange = (e)=> {
        state.selectArr = e
      }
      const getRowKey = (row) => {
        return row.AIID
      }
      const querySearch = (queryString, cb) => {
        const restaurants = state.WHdata
        const results =
          queryString && queryString != 'null'
            ? restaurants.filter(createFilter(queryString))
            : restaurants
        console.log(results)
        // 调用 callback 返回建议列表的数据
        cb(results)
      }
      const createFilter = (queryString) => {
        return (restaurant) => {
          console.log(restaurant)
          return (
            restaurant.value
              .toLowerCase()
              .indexOf(queryString.toLowerCase()) === 0
          )
        }
      }
      //列表编辑
      const handleEdit = (row, type) => {
        if (row && row.AIID) {
          state['editRef'].showEdit(row, type)
        } else {
          state['editRef'].showEdit(state.queryForm, type)
        }
      }
      //页面刷新
      const settingsStore = useSettingsStore()
      const { theme } = storeToRefs(settingsStore)
      const $pub = inject('$pub')
      const refreshRoute = () => {
        $pub('reload-router-view')
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.AIID) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await DelItem({ aiid: row.AIID })
            //删除列表默认回到第一页
            $baseMessage(message, 'success', 'vab-hey-message-success')
            // refreshRoute()
            fetchData()
          })
        }
      }
      const WHGetPageData1 = async () => {
        const params = {
          pageNo: 1,
          pageSize: 10,
          wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
          export: true,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
        }
        const data = await SelAllItemWHUnit(params)
        if (data.data.data && data.data.data.length > 0) {
          data.data.data.map((item) => {
            item.value = item.whUnit
          })
        }
        state.WHdata = data.data.data
      }
      //菜单表格
      const fetchData = async (val) => {
        //wheres重新赋值
        const params = JSON.parse(JSON.stringify(state.queryForm))
        //搜索
        if (val == 'search') {
          // params.pageNo = 1
          const searcharr = []
          if (params.search != '') {
            searcharr.push({
              name: 'OldSpec',
              value: params.search,
              displayType: 'like',
            })
          }

          if (params.search1 != '') {
            searcharr.push({
              name: 'NewCode',
              value: params.search1,
              displayType: 'like',
            })
          }
          if (params.search2 != '') {
            searcharr.push({
              name: 'NewName',
              value: params.search2,
              displayType: 'like',
            })
          }
          if (params.search3 != '') {
            searcharr.push({
              name: 'OldCode',
              value: params.search3,
              displayType: 'like',
            })
          }
          if (params.search4 != '') {
            searcharr.push({
              name: 'WHUnit',
              value: params.search4,
              displayType: 'like',
            })
          }
          if (params.searchValidDate != '') {
            searcharr.push({
              name: 'ValidDate',
              value: params.searchValidDate,
              displayType: 'like',
            })
          }
          if (params.searchBigCateCode != '') {
            searcharr.push({
              name: 'BigCateCode',
              value: params.searchBigCateCode,
              displayType: 'like',
            })
          }
          if (params.search5&&params.search5.length>0&&params.search5!=null&&params.search5!='null') {
            searcharr.push({
              name: 'CreateDate',
              value: params.search5[0],
              displayType: 'ThanOrEqual',
            })
          }
          if (params.search5&&params.search5.length>0&&params.search5!=null&&params.search5!='null') {
            searcharr.push({
              name: 'CreateDate',
              value: params.search5[1],
              displayType: 'LessOrequal',
            })
          }
          params.wheres = JSON.stringify(searcharr)
        } else {
          params.wheres = `[{"name":"NewName","value":"","displayType":"like"}]`
        }
        state.listLoading = true
        const {
          data: { rows, total },
        } = await wms_itemData(params)
        state.list = rows
        state.total = total
        state.listLoading = false
        console.log(state.list)
      }
      //分页条数切换
      const handleSizeChange = (val) => {
        console.log(val)
        state.queryForm.pageSize = val
        state.list = []
        fetchData('search')
      }
      //分页切换
      const handleCurrentChange = (val) => {
        console.log(val)
        state.queryForm.pageNo = val
        state.list = []
        fetchData('search')
      }
  const deletedBatchFn = async () => {
    const arrList = []
    if(state.selectArr&&state.selectArr.length>0) {
      state.selectArr.map((item) =>{
        arrList.push({
          aiid: item.AIID
        })
      })
    }else {
      ElMessage({
          message: '请选择至少一条要删除的数据',
          type: 'warning',
        })
      return
    }
    $baseConfirm(translate('你确定要删除吗'), null, async () => {
      const data = await BatchDelItem(arrList)
      if (data.code === '200') {
        ElMessage({
          message: data.message,
          type: 'success',
        })
      }
      fetchData()
    })
  }
      //菜单表格
      const getCompanyTree = async () => {
        const {
          data: { data },
        } = await getTree()
        if (data) state.tree = JSON.parse(data)
      }
      // 下载物资表
      const download = async () => {
        const data = await Wms_itemDown()
        if (data) {
          console.log(data)
          const blob = new Blob([data])
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = `物资表.xlsx`
          link.href = url
          link.click()
        }
      }
      // 导出
      const exportFn = async (val) => {
        state.listLoading = true
        // params.pageNo = 1
        const params = JSON.parse(JSON.stringify(state.queryForm))
        const searcharr = []
        if (val == 'search') {
          // params.pageNo = 1
          const searcharr = []
          if (params.search != '') {
            searcharr.push({
              name: 'OldSpec',
              value: params.search,
              displayType: 'like',
            })
          }

          if (params.search1 != '') {
            searcharr.push({
              name: 'NewCode',
              value: params.search1,
              displayType: 'like',
            })
          }
          if (params.search2 != '') {
            searcharr.push({
              name: 'NewName',
              value: params.search2,
              displayType: 'like',
            })
          }
          if (params.search3 != '') {
            searcharr.push({
              name: 'OldCode',
              value: params.search3,
              displayType: 'like',
            })
          }
          if (params.search4 != '') {
            searcharr.push({
              name: 'WHUnit',
              value: params.search4,
              displayType: 'like',
            })
          }
          if (params.searchValidDate != '') {
            searcharr.push({
              name: 'ValidDate',
              value: params.searchValidDate,
              displayType: 'like',
            })
          }
          if (params.searchBigCateCode != '') {
            searcharr.push({
              name: 'BigCateCode',
              value: params.searchBigCateCode,
              displayType: 'like',
            })
          }
          if (params.search5&&params.search5.length>0&&params.search5!=null&&params.search5!='null') {
            searcharr.push({
              name: 'CreateDate',
              value: params.search5[0],
              displayType: 'ThanOrEqual',
            })
          }
          if (params.search5&&params.search5.length>0&&params.search5!=null&&params.search5!='null') {
            searcharr.push({
              name: 'CreateDate',
              value: params.search5[1],
              displayType: 'LessOrequal',
            })
          }
          params.wheres = JSON.stringify(searcharr)
        } else {
          params.wheres = `[{"name":"NewName","value":"","displayType":"like"}]`
        }

        state.queryForm.wheres = params.wheres
        const data = await Wms_All_ItemExport(state.queryForm)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.download = `物资对应${time}.xlsx`
        link.href = url
        link.click()
        state.listLoading = false
      }
      const handleError = () => {}
      const beforeUpload = () => {}
      const uploadFn = async () => {
        state.listLoading = true
        state.headers = state.headers = {
          Authorization: `Bearer ${token}`,
        }
        state.action = `${baseURL}/Wms_All_Item/ImportAllItem`
      }
      const handleSuccess = (data) => {
        console.log(data)
        if (data.code === '200') {
          $baseMessage(
            translate('导入成功'),
            'success',
            'vab-hey-message-success'
          )
          fetchData()
        } else {
          $baseMessage(data.message, 'error', 'vab-hey-message-error')
        }
        state.listLoading = true
      }
      const deletedSX = () => {
            state.dialogVisible1 = true
      }
      const handleClose1 = () => {
            state.dialogVisible1 = false
      }
      const confirm1 = async () => {
        if(!state.searchInfo || state.searchInfo.length<=0 ||state.searchInfo===null || state.searchInfo ==='null'){
              ElMessage({
              message: '请选择要删除的时间区间',
              type: 'warning',
            })
          return
        }
      $baseConfirm(translate('你确定要删除吗'), null, async () => {
      const params = {
            begindate:state.searchInfo[0]+' 00:00:00',
            enddate: state.searchInfo[1]+' 23:59:59'
      }
      const data = await DateDelAllItem(params)
      if (data.code === '200') {
        ElMessage({
          message: data.message,
          type: 'success',
        })
        fetchData()
      }

    })
    }
      const resetFn = () => {
        state.queryForm.seach = ''
        state.queryForm.seach1 = ''
        state.queryForm.seach2 = ''
        state.queryForm.seach3 = ''
        state.queryForm.pageNo = 1
        state.queryForm.pageSize = 10
        fetchData()
      }
        //复制标识
        const copyToClipboard = async(val)=> {
        if (navigator.clipboard && window.isSecureContext) {
          try {
          console.log(navigator.clipboard)
          console.log(window.isSecureContext)
          await navigator.clipboard.writeText(val)
          $baseMessage(
            translate('复制成功'),
            'success',
            'vab-hey-message-success'
          )
          } catch (err) {
            $baseMessage(
            translate('复制失败'),
            'error',
            'vab-hey-message-error'
          )
          }

        }else {
          // 创建text area
        const textArea = document.createElement("textarea")
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute"
        textArea.style.opacity = 0
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej()
          textArea.remove()
        }).then(() => {
          $baseMessage(
            translate('复制成功'),
            'success',
            'vab-hey-message-success'
          )
          }).catch((err) => {
            $baseMessage(
            translate('复制失败'),
            'error',
            'vab-hey-message-error'
          )
          })
        }

  }

      onMounted(() => {
        getCompanyTree()
        fetchData()
        WHGetPageData1()
      })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        // handleNodeClick,
        Delete,
        Plus,
        Search,
        handleCurrentChange,
        handleSizeChange,
        refreshRoute,
        getCompanyTree,
        MenuAuth,
        download,
        exportFn,
        handleError,
        uploadFn,
        beforeUpload,
        handleSuccess,
        translate,
        querySearch,
        handleSelect,
        createFilter,
        WHGetPageData1,
        resetFn,
        tableRowClassName,
        handleSelectionChange,
        getRowKey,
        deletedBatchFn,
        copyToClipboard,
        deletedSX,
        handleClose1,
        confirm1,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.menu-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }
  .mr10 {
    margin-right: 10px;
  }
  .w164 {
    width: 164px !important;
  }
  .w120 {
    display: inline-block;
    width: 100px;
    text-align: right;
  }
  .ml10 {
    margin-left: 10px;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .iconcolor {
      color: #409eff;
    }
    .ml {
      display:inline-block;
      margin-right:10px;
      margin-left:10px;
    }
</style>
